<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :modal="form" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="form.userName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">部门树形选中</h4>

    <el-tree :data="deptList" show-checkbox node-key="deptId" :default-expanded-keys="defaultExpandedDept" ref="tree"
      :default-checked-keys="defaultCheckDept" :props="defaultProps">
    </el-tree>
    <div class="buttons">
      <el-button @click="getCheckedKeys">保存</el-button>
      <el-button @click="cancel">取消</el-button>

    </div>
    <div>
      <h4 class="form-header h4">部门列表</h4>
      <el-table v-loading="loading" :data="deptList2" style="width: 100%;margin-bottom: 20px;" border default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="handleSelectionChange"
        :row-key="getRowKey" ref="table" stripe @select="mySelect">
        <!--
          
          :tree-props="{children: 'children', hasChildren: 'hasChildren'} 第一个参数表示树形数据，第二个参数表示是否有子节点；渲染树形数据时，必须要指定 row-key。

          stripe 斑马纹,Table Attributes ，
        :row-class-name="tableRowClassName" 自定义颜色表格
         @row-click="clickRow" 和@selection-change 冲突了，@selection-change起作用了

         :default-checked-keys="defaultCheckDept"  default-checked-keys 是树形el-tree的方法，不是el-table的，
         所以不能用在这里默认选中
         -->

        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column prop="deptName" label="部门名" sortable width="180">
        </el-table-column>
        <el-table-column prop="leader" label="负责人" sortable width="180">
        </el-table-column>
        <el-table-column prop="phone" label="地址">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
      </el-table>

    </div>
    <el-button @click="saveDept">保存</el-button>
    <el-button @click="close">返回</el-button>
    <el-button @click="clearSelection">清除选中</el-button>

    <el-table :data="tableData" ref="myTableData" @selection-change="handleSelectionChange2">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
    </el-table>
  </div>

</template>

<script>
import { getDepts, getUserDept, myDeptTree } from '@/api/wu/myDept'
import { getUserById } from '@/api/wu/myUser'
import TreeSelect from '@riophae/vue-treeselect'
export default {
  name: "dept",
  components: {
    TreeSelect
  },
  data() {
    return {
      //遮罩层
      loading: true,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      deptIds: [],
      deptList: [],
      deptList2: [],
      //用户信息
      form: {},
      refreshTable: null,
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      //默认展开
      defaultCheckDept: [],
      //默认选中
      defaultExpandedDept: [],
      deptIds2: [],
      tableData: [
        { id: 1, name: '张三', selected: true },
        { id: 2, name: '李四', selected: false },
        // 其他行数据  
      ]
    }
  },
  created() {
    let userId = this.$route.params && this.$route.params.userId;
    if (userId) {
      this.loading = true;
      getUserById(userId).then(response => {
        this.form = response.data;
        this.defaultCheckDept.push(response.data.deptId);
        this.defaultExpandedDept.push(response.data.deptId);

        //列表默认选中的部门
        this.deptIds.push(response.data.deptId);
      });

      myDeptTree(userId).then(response => {
        this.deptList = response.data;
        this.deptList2 = response.data;

        //遍历children,判断是否选中
        this.doTableSelected(this.deptList2);

        /*deptList2只有一个，选中的元素在他的子节点children中，
         这里遍历节点的时候只有一个100，所以选不中，如果要搞成树形结构，且有选中标志 selected=true，得让接口返。
      
        */
        // this.deptList2.forEach((row) => {
        //   //include包含某个元素
        //   console.log('this.deptIds : ' + this.deptIds);
        //   if (this.deptIds.includes(row.deptId)) {
        //     row.selected = true;
        //   } else {
        //     row.selected = false;
        //   }
        // });
        /*this.$nextTick 获取更新后的dom节点信息
        这是一个树形结构，属性结构deptList2只有一个几点，都在children下面
        还有 this.$nextTick 执行在 myDeptTree前面，得放在MyDeptTree里面，this.$nextTick 是role.vue里面用到了
        */
        // this.$nextTick(() => {
        //   this.deptList2.forEach((row) => {
        //     if (this.deptIds.indexOf(row) != -1) {
        //       this.$refs.table.toggleRowSelection(row);
        //     }
        //   })
        // });
      });


      // 接口返了selected=true，没起作用，还是用toggleRowSelection才能选中
      this.$nextTick(() => {
        this.tableData.forEach((row) => {
          if (row.selected) {
            this.$refs.myTableData.toggleRowSelection(row);
          }
        })
      });
      this.loading = false;
    }
  },
  methods: {
    //列表选中
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //颜色修改
    tableRowClassName({ row, rowIndex }) {
      // if (rowIndex % 2 === 0) {
      //   return 'warning-row';
      // } else {//if (rowIndex % 3 === 0)
      return 'success-row';
      // }
      // return '';
    },
    //返回
    close() {
      const obj = { path: '/system/wuuser' }
      this.$tab.closeOpenPage(obj);
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.deptId;
    },
    /**
     * 官方文档 
     * 事件： select，用法是 @select="mySelect" v-on
     * Table Attributes(属性): row-key 用法是 :row-key, v-bind='row-key'
     * Table Methods： clearSelection 用法是@click='xxx'，clearSelection是原生方法  v-click
     * 
    */
    mySelect(selection, row) {
      console.log("rowclick: " + selection)
      console.log("rowclick: " + row)
    },
    //清除选中
    clearSelection() {
      this.$refs.table.clearSelection();
    },
    //保存部门
    saveDept() {
      console.log(this.deptIds2);
      const userId = this.form.userId;
      const deptIdList = this.deptIds2.join(",")
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.deptIds2 = selection.map((item) => item.deptId);
    },
    //单击选中行数据 
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    //获取选中的key
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys());
    },
    cancel() {
      location.reload();
    },
    handleSelectionChange2() { },
    //递归，遍历选中
    doTableSelected(list) {
      list.forEach((row) => {
        if (row.selected) {
          this.$refs.table.toggleRowSelection(row);
        }
        if (Array.isArray(row.children) && row.children.length > 0) {
          this.doTableSelected(row.children);
        }
      });

    }
  }
}

</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>